import React, { memo, useEffect, useRef, useState } from "react";
import * as echarts from 'echarts';
import classNames from 'classnames';


export interface Props {
  className?: string;
  title?: string;
  state: unknown
}



function PwmOscilloscope(props: Props) {
  const { state } = props;
  const SLOTS = 10;
  const SAMPLES_PER_CYCLE = 100;

  const chartRef = useRef(null);
  const chartInstance = useRef(null);


  useEffect(() => {
    if (!chartRef.current) return;
    chartInstance.current = echarts.init(chartRef.current, null, {
      renderer: "canvas",
    });

    chartInstance.current.setOption({
      animation: false,
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['CPU温度']
      },
      grid: {
        top: '10',
        left: '10',
        right: '10',
        bottom: '40',
        containLabel: true
      },
      xAxis: {
        type: "value",
        min: 0,
        max: SLOTS,
        axisLine: { show: true },   // 显示底部的 X 轴线
        axisTick: { show: true },
        axisLabel: { show: false },
        splitLine: { show: false }, // 不显示网格线
      },
      yAxis: {
        type: "value",
        min: 0,
        max: 1,
        axisLine: { show: true },   // 显示左侧的 Y 轴线
        axisTick: { show: true },
        axisLabel: { show: true },
        splitLine: { show: false }  // 不显示横向网格线
      },
      series: [
        {
          name: "A电机",
          type: "line",
          step: "middle",
          showSymbol: false,
          data: [],
        },
      ],
    });

    // resize
    const resize = () => chartInstance.current.resize();
    window.addEventListener("resize", resize);
    return () => {
      window.removeEventListener("resize", resize);
      chartInstance.current?.dispose();
    };
  }, []);

  const buildPlotData = () => {
    const pts = [];
    for (let i = 0; i < state.length; i++) {
      const duty = Math.max(0, Math.min(1, (state[i] / 100) || 0));
      for (let s = 0; s < SAMPLES_PER_CYCLE; s++) {
        const frac = s / SAMPLES_PER_CYCLE;
        const x = i + frac;
        const y = frac < duty ? 1 : 0;
        pts.push([x, y]);
      }
      pts.push([i + 1 - 1e-9, 0]);
    }
    return pts;
  };

  const renderChart = () => {
    if (!chartInstance.current) return;
    chartInstance.current.setOption({
      xAxis: { min: 0, max: SLOTS },
      series: [{ data: buildPlotData() }],
    });
  };

  useEffect(() => {
    renderChart();
  }, [state]);


  return (
    <div ref={chartRef} className={classNames('size-full h-56', props.className)}></div>
  );
};

export default memo(PwmOscilloscope)

